package com.support.net

import androidx.lifecycle.ViewModel
import com.google.gson.Gson
import com.support.utils.Constant
import com.support.utils.SPUtils
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


object Http {
    /**
     * 日志打印拦截器
     */
    private val logger = HttpLoggingInterceptor()

    /**
     * okhttp客户端
     */
    private val client: OkHttpClient

    /**
     * Retrofit实例
     */
    private val retrofit: Retrofit

    /**
     * API缓存，缓存已创建过的api对象，拿空间换时间的一种做法
     */
    private val apiCache = mutableMapOf<String, Any>()

    /**
     * 获取wsKey
     */
    private val wsKey: String
        get() {
            return if (SPUtils.getString(Constant.SPKeys.a2) == "")
                "AAJhLcMQAECo_yJca9uF78DFfTYFqTqqrRrpiyzt7LH6GJsgY-QEToHuat6K_-Nhc5CLfS9FsqaMDEQaCz6QWzoo99mp1BXs"
            else
                SPUtils.getString(Constant.SPKeys.a2)
        }


    /**
     * 获取pin
     */
    val pin: String
        get() {
            return if (SPUtils.getString(Constant.SPKeys.pin) == "")
                "fei901011_m"
            else
                SPUtils.getString(Constant.SPKeys.pin)
        }


    /**
     * 获取farmCode
     */
    val farmCode: Long
        get() {
            return if (SPUtils.getLong(Constant.SPKeys.farmCode) == -1L)
                28L
            else
                SPUtils.getLong(Constant.SPKeys.farmCode)
        }


    /**
     * 获取统一的header
     */
    val headers: Map<String, String>
        get() {
            val appParams = Gson().toJson(mapOf("appid" to "1458", "ticket_type" to "app"))
            return mutableMapOf(
                "Cookie" to "ws_key=$wsKey",
                "LOP-DN" to "jdfarm.mrd.jd.com",
                "AppParams" to appParams,
                "content-type" to "application/otcet-stream"
            )
        }

    /**
     * 初始化
     *
     */
    init {
        logger.level = HttpLoggingInterceptor.Level.BODY

        client = OkHttpClient
            .Builder()
            .callTimeout(60, TimeUnit.SECONDS)
            .connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .addInterceptor(logger)
            .build()
        retrofit = Retrofit
            .Builder()
            .baseUrl("https://uat-proxy.jd.com/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    /**
     * 注入viewModel
     */
    fun inject(viewModel: ViewModel) {
        /**
         * 获取需要注入对象的class对象
         */
        val clazz = viewModel::class.java

        /**
         * 获取类的成员变量，包括私有
         */
        val fields = clazz.declaredFields

        /**
         * 遍历成员变量，找到被@API注解的变量
         */
        fields.forEach {
            if (it.isAnnotationPresent(API::class.java)) {
                //开放访问权限
                it.isAccessible = true
                try {
                    //为被注解的成员变量赋值
                    it.set(viewModel, create(it.type))
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    /**
     * 获取实例
     * @param clazz api的class对象
     */
    private fun <T> create(clazz: Class<T>): T {

        if (apiCache[clazz.name] == null) {
            apiCache[clazz.name] = retrofit.create(clazz)!!
        }
        return apiCache[clazz.name] as T
    }
}